// 1.0 引入axios
import axios from 'axios'
// qs 可以把对象 转换为 k=v&k=v 这种格式的字符串
import qs from 'qs'

import local from '@/utils/local.js'

import 'nprogress/nprogress.css'
import NProgress from 'nprogress'

// axios的配置项
axios.defaults.baseURL = 'http://127.0.0.1:5000'
// 2.1 设置了超时处理
axios.defaults.timeout = 5000

// 请求拦截器
axios.interceptors.request.use(config => {
  NProgress.start()
  const token = local.get('token')
  if (token) {
    config.headers.Authorization = token
  }
  return config
})

axios.interceptors.response.use(res => {
  NProgress.done()
  return res
})

export default {
  get(url, params) {
    return new Promise((resolve, reject) => {
      axios
        .get(url, { params })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err)
        })
    })
  },

  post(url, query) {
    return new Promise((resolve, reject) => {
      axios
        .post(url, qs.stringify(query))
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err)
        })
    })
  }
}
